from django.shortcuts import render
from django.views import View
from django.core.cache import cache
from django import http
from apps.areas.models import Area

# Create your views here.


class ProvinceAreasView(View):
    """查询省份数据"""
    def get(self, request):
        # 读取缓存
        province_dict_list = cache.get('province_list')
        if province_dict_list:
            return http.JsonResponse({'code': '0', 'errmsg': 'OK', 'province_list': province_dict_list})

        # 查询省份数据
        province_model_list = Area.objects.filter(parent=None)

        # 将查询集列表转成字典列表
        province_dict_list = []
        for province_model in province_model_list:
            # 把模型数据转成字典数据
            province_dict = {
                "id": province_model.id,
                "name": province_model.name,
            }
            province_dict_list.append(province_dict)

        # 缓存省份字典列表
        cache.set('province_list', province_dict_list, 3600)

        # 响应结果
        return http.JsonResponse({'code': '0', 'errmsg': 'OK', 'province_list': province_dict_list})


class SubAreasView(View):
    """查询城市或者区县数据"""
    def get(self, request, parentid):
        # 读取缓存
        sub_data = cache.get('sub_data_%s' % parentid)
        if sub_data:
            return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'sub_data': sub_data})

        # 查询当前的父级地区：省份或者城市
        parent_area = Area.objects.get(id=parentid)
        # 查询当前父级地区的子级
        sub_model_list = parent_area.subs.all()

        # 将子级的模型列表转成字典列表
        subs = []
        for sub_model in sub_model_list:
            sub_dict = {
                "id": sub_model.id,
                "name": sub_model.name,
            }
            subs.append(sub_dict)

        # 自己数据：城市或者区县
        sub_data = {
            "id": parent_area.id,
            "name": parent_area.name,
            "subs": subs,
        }

        # 缓存子级数据
        cache.set('sub_data_%s' % parentid, sub_data, 3600)

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'sub_data': sub_data})